﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using CqBuiltinService.Controller;
using CqCore.Logging;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SuperShopInfrastructure.Extensions;
using SuperShopInfrastructure.Models.Order;
using SuperShopInfrastructure.Models.Ship;
using SuperShopInfrastructure.Static;
using SuperShopService.IServices;

namespace SuperShopApi.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class OrderController : ControllerBase
    {
        private readonly IOrderService orderService;
        private readonly IHttpContextAccessor httpContext;
        private readonly ILogRecorder<OrderController> logRecorder;

        public OrderController(
            IOrderService orderService,
            IHttpContextAccessor httpContext,
            ILogRecorder<OrderController> logRecorder)
        {
            this.orderService = orderService;
            this.httpContext = httpContext;
            this.logRecorder = logRecorder;
        }

        /// <summary>
        /// 获取订单详情
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        [HttpGet("{orderId}")]
        [ProducesResponseType(typeof(OrderDetail_InfoViewModel), (int)HttpStatusCode.OK)]
        [ProducesResponseType(typeof(string), (int)HttpStatusCode.BadRequest)]
        public async Task<IActionResult> GetDetail([FromRoute] int orderId)
        {
            var res = await orderService.GetDetail(orderId);
            return Ok(res);
        }

        /// <summary>
        /// 搜索订单列表
        /// </summary>
        /// <param name="criteria"></param>
        /// <returns></returns>
        [HttpPost("search/list")]
        [ModelValidate]
        [ProducesResponseType(typeof(List<OrderListViewModel>), (int)HttpStatusCode.OK)]
        [ProducesResponseType(typeof(string), (int)HttpStatusCode.BadRequest)]
        public async Task<IActionResult> GetOrderList([FromBody] QueryOrderListCriteria criteria)
        {
            var decErrMsg = criteria.DecryptProperty();
            if (!string.IsNullOrEmpty(decErrMsg))
                return BadRequest(decErrMsg);
            var res = await orderService.GetOrderList(criteria);
            return Ok(res);
        }

        /// <summary>
        /// 申请售后
        /// </summary>
        /// <param name="orderid"></param>
        /// <param name="userid"></param>
        /// <returns></returns>
        [HttpGet("apply/service")]
        [ProducesResponseType(typeof(bool), (int)HttpStatusCode.OK)]
        [ProducesResponseType(typeof(string), (int)HttpStatusCode.BadRequest)]
        public async Task<IActionResult> ServiceOrder([FromQuery] int orderid, [FromQuery] string userid)
        {
            var _userid = ToolManager.DecryptParms(userid);
            if (_userid == null)
                return BadRequest("非法参数");
            var res = await orderService.ServiceOrder(orderid, _userid.ToInt());
            if (!res)
                return BadRequest("申请失败");
            return Ok(true);
        }

        /// <summary>
        /// 创建订单
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpPost("")]
        [ModelValidate]
        [ProducesResponseType(typeof(CreateOrderResultViewModel), (int)HttpStatusCode.OK)]
        [ProducesResponseType(typeof(string), (int)HttpStatusCode.BadRequest)]
        public async Task<IActionResult> CreateOrder([FromBody] CreateOrderCommand command)
        {
            var decErrMsg = command.DecryptProperty();
            if (!string.IsNullOrEmpty(decErrMsg))
                return BadRequest(decErrMsg);
            if (command.ConsigneeId <= 0 || command.ShipAmount < 0 || command.CreateOrder_ProductItems == null || command.CreateOrder_ProductItems.Count <= 0)
                return BadRequest("非法参数");
            var res = await orderService.CreateOrder(command);
            if (!res.IsSuccess)
                return BadRequest(res.FailureReason);
            return Ok(res.GetData());
        }

        /// <summary>
        /// 微信支付小程序回调
        /// </summary>
        /// <returns></returns>
        [HttpPost("wxCallBack")]
        public async Task<IActionResult> WxCallBack()
        {
            //接收从微信后台POST过来的数据
            System.IO.Stream s = httpContext.HttpContext.Request.Body;
            int count = 0;
            byte[] buffer = new byte[1024];
            StringBuilder builder = new StringBuilder();
            while ((count = s.Read(buffer, 0, 1024)) > 0)
            {
                builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
            }
            s.Flush();
            s.Close();
            s.Dispose();
            logRecorder.Info(new EventData() {
                Type = "WxCallBack",
                Message = "微信回调返回数据",
                Labels = {
                    ["data"] = builder.ToString()
                }
            });
            var res = await orderService.WxCallBack(builder);
            return Ok(res.ToXml());
        }

        //deleted h5回调

        /// <summary>
        /// 获取微信支付模型
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="orderno"></param>
        /// <returns></returns>
        [HttpGet("payData")]
        [ProducesResponseType(typeof(CreateOrderResultViewModel), (int)HttpStatusCode.OK)]
        [ProducesResponseType(typeof(string), (int)HttpStatusCode.BadRequest)]
        public async Task<IActionResult> GetPayData([FromQuery] string userid, [FromQuery] string orderno)
        {
            if (string.IsNullOrEmpty(userid) || string.IsNullOrEmpty(orderno))
                return BadRequest("非法参数");
            string _userid = ToolManager.DecryptParms(userid);
            if (_userid == null)
                return BadRequest("用户异常");
            //从redis获取拉起支付所需的缓存数据
            var res = await orderService.GetPayData(_userid,orderno);
            if (res == null)
                return BadRequest("获取支付数据失败");
            return Ok(res);
        }

        /// <summary>
        /// 计算运费
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpPost("shipAmount")]
        [ModelValidate]
        [ProducesResponseType(typeof(decimal), (int)HttpStatusCode.OK)]
        [ProducesResponseType(typeof(string), (int)HttpStatusCode.BadRequest)]
        public async Task<IActionResult> CountShipAmount([FromBody] CountShipAmountCommand command)
        {
            var decErrMsg = command.DecryptProperty();
            if (!string.IsNullOrEmpty(decErrMsg))
                return BadRequest(decErrMsg);
            foreach (var item in command.Products)
            {
                var _productId =ToolManager.DecryptParms(item.ProductId);
                if (_productId == null)
                    return BadRequest("非法参数");
                item.ProductId = _productId;
            }
            var res = await orderService.CountShipAmount(command);
            if (!res.IsSuccess)
                return BadRequest(res.FailureReason);
            return Ok(res.GetData());
        }
    }
}